class Topic < ActiveRecord::Base
  
  belongs_to :forum
  has_many :posts, :dependent => :destroy, :order => 'posts.created_at'
  has_many :subscriptions, :dependent => :destroy
  
  validates_presence_of :name
  
  def self.find_ordered(options = {})
    options.reverse_merge! :order => 'sticky DESC, posts.created_at DESC', :include => [:posts, :forum]
    find(:all, options)
  end  
  
  def self.find_recent(options = {})
    options.reverse_merge! :order => 'posts.created_at DESC', :include => [:posts, :forum]
    find(:all, options)
  end
  
  def self.find_unanswered(options = {})
    options.reverse_merge! :include => [:posts, :forum], :conditions => unanswered_sql_condition, :order => 'posts.created_at DESC'
    find(:all, options)
  end
  
  def self.count_unanswered
    # TODO we should use the SQL_CALC_FOUND_ROWS here, but that will make it dependent on mysql.
    Topic.count_by_sql("select count(*) from topics left join forums on(forums.id = topics.forum_id) where "+unanswered_sql_condition)
  end
  
  def self.unanswered_sql_condition
    "locked=0 AND sticky=0 AND forums.private=0 and (select count(*) from posts where topics.id = posts.topic_id) = 1"
  end
  
  def self.find_unread(user, options = {})
    options.reverse_merge! :include => [:posts, :forum], :conditions => [unread_sql_condition(user)], :order => 'posts.created_at DESC'
    find(:all, options)
  end

  def self.count_unread(user)
    # TODO we should use the SQL_CALC_FOUND_ROWS here, but that will make it dependent on mysql.
    Topic.count_by_sql("select count(*) from topics left join posts on(posts.topic_id = topics.id) where "+unread_sql_condition(user))
  end
    
  def self.unread_sql_condition(user)
  	"(select count(*) from posts where topics.id = posts.topic_id and posts.created_at >= '#{user.last_session_at.to_formatted_s(:db)}') >= 1"
  end
  
  def self.find_subscriptions(user)
    find(:all, :order => 'posts.created_at DESC', 
      :conditions => ["subscriptions.user_id = ?", user.id],
      :include => [:posts, :forum, :subscriptions])
  end
  
  def last_post
    posts.find(:first, :order => 'created_at DESC')
  end
  
  def first_post # there's probably a better way to do this
    posts.find(:first, :order => 'created_at')
  end
  
  def owned_by?(user)
    first_post.owned_by? user
  end
  
  def moderated_by?(user)
    forum.moderated_by? user
  end
  
  def moderatorship_for_user(user)
    forum.moderatorship_for_user user
  end
  
  def private?
    forum.private?
  end
  
  def link # REFACTORME Does this really belong in the model?
    "/topics/#{id}"
  end
  
  def body
    first_post.content
  end
  
  def created_at
    first_post ? first_post.created_at : Time.now
  end
  
  def validate
    errors.add :forum_id, 'cannot be a category' if forum && forum.category?
  end
end
